<template>
  <div class="app-container sendMsg">
    <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules" style="text-align: center;">
      <el-form-item label="标题："  prop="title" required>
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="内容：" prop="content" required>
        <el-input type="textarea" rows="13"  v-model="form.content"></el-input>
      </el-form-item>
      <el-form-item label="接收人：" required>
        <dataTree
          class="tree-border"
          :data="form.receiveUserIds"
          show-checkbox
          :default-expand-all="false"
          ref="empTree"
          node-key="id"
          :filter-node-method="filterNode"
          empty-text="加载中，请稍候"
          :props="defaultProps"
          @check-change="getTreeCheckedKeys"
          @node-click="handleNodeClick"
          :default-expanded-keys="treeExpandData"
          highlight-current
        />
      </el-form-item>
      <el-form-item>
        <el-button size="small" class="resetBtn" @click="resetForm">重置</el-button>
        <el-button size="small" class="add2Btn" @click="submitForm">发送</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import userApi from '@/api/user'
import messageApi from '@/api/message'
import dataTree from '@/components/tree/src/tree.vue'

export default {
  components: { dataTree },
  data () {
    return {
      treeExpandData: [],
      parentList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      form: {
        title: '',
        content: '',
        receiveUserIds: []
      },
      formLoading: false,
      selectLoading: false,
      options: [],
      rules: {
        title: [
          { required: true, message: '请输入消息标题', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入消息内容', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.findZNodes()
  },
  methods: {
    getRoleTreeRootNode(res) {
      this.treeExpandData.push(res[0].id)      
    },
    //加载修改树结构json
    findZNodes() {
      userApi.getUserDepartsTree().then(res => {
        const mapTree = org => {
            const haveChildren = Array.isArray(org.children) && org.children.length > 0
            let newId
            // if (org.children.length  == 0) {
            if (org.type == 2) {
              let pLen =  (org.parentid).toString().length
              let zeroCount = 5 - pLen
              let zeroStr = '',
              zero = '0'
              let i
              for (i = 0;i < zeroCount; i++) {
                zeroStr += zero
              }
              newId = org.parentid + zeroStr + org.id
            }

            // id : org.children.length  > 0 ? org.id : newId,
            return {
                type: org.type,
                id: org.type == 1 ? org.id : newId,
                label: org.label,
                parentid: org.parentid,
                children:haveChildren ? org.children.map(i => mapTree(i)) : [],
            }
        };
        let treeNewData = res.response.map(org => mapTree(org) )
        // console.log('newTree:', treeNewData)
        // this.form.receiveUserIds = res.response
        this.form.receiveUserIds = treeNewData
        this.getRoleTreeRootNode(res.response)
      })
    },
    // 根据当前获取的tree节点信息查找父节点
    getParent (node) {
      if(node.isLeaf == false && node.parent.parent == null){ //
          this.parentList.push(node.data);
      }else{
          if(node.isLeaf == false && node.parent.parent != null ){ //
            this.parentList.push(node.data);
            this.getParent(node.parent)
          }else if(node.isLeaf == true && node.parent.parent != null){
              this.parentList.push(node.data);
              this.getParent(node.parent)
          }
      }
    },
    handleNodeClick(item, node) {
      this.parentList = [];
      this.getParent(node);
    },
    // 共三个参数，依次为：1. 传递给 data 属性的数组中该节点所对应的对象、2. 节点本身是否被选中、3. 节点的子树中是否有被选中的节点
    getTreeCheckedKeys(data, checked) {
      let arr = this.$refs.empTree.getCheckedKeys()
      let newarr = []
      this.$refs.empTree.setCheckedKeys([])
      arr.forEach((item,index) => {
        if (typeof item ==  'string') {
          newarr.push(item)
          this.$refs.empTree.setChecked(item, true, false)
        } else {
          this.$refs.empTree.setChecked(item, false, false)
        }
        
      })
      // this.$refs.empTree.setCheckedKeys([])
      // this.$refs.empTree.setCheckedKeys(newarr)
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getUserByUserName (query) {
      let _this = this
      if (query !== '') {
        _this.selectLoading = true
        userApi.selectByUserName(query).then(re => {
          _this.selectLoading = false
          _this.options = re.response
        })
      } else {
        _this.options = []
      }
    },
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (_this.$refs.empTree.getCheckedKeys().length == 0) {
            _this.$message.error('请勾选员工！')
            _this.formLoading = false
            return
          }
          this.formLoading = true

          const selectedKeysArr = this.$refs.empTree.getCheckedKeys()
          let newArr = []
          selectedKeysArr.forEach(item => {
            if (typeof item == 'string') {
              newArr.push(item.slice(5))
            }
          })
          // this.form.receiveUserIds  = this.$refs.empTree.getCheckedKeys()
          this.form.receiveUserIds  = newArr
          messageApi.send(this.form).then(data => {
            if (data.code === 1) {
              _this.$message.success(data.message)
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/message/list')
              })
            } else {
              _this.$message.error(data.message)
              _this.$refs.empTree.setCheckedKeys([])
              _this.formLoading = false
              _this.findZNodes()
            }
          }).catch(e => {
            _this.$refs.empTree.setCheckedKeys([])
            _this.formLoading = false
            _this.findZNodes()
          })
        } else {
          return false
        }
      })
    },
    resetForm () {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        title: '',
        content: '',
        receiveUserIds: []
      }
      this.$refs.empTree.setCheckedKeys([])
      this.form.id = lastId
      this.findZNodes()
    },
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  }
}
</script>

<style rel="stylesheet/scss" lang='scss'>
.sendMsg .el-form-item--medium .el-form-item__content {
  line-height: 36px;
  width: 84%;
}

.sendMsg .el-select {
  display: inline-block;
  position: relative;
  width: 100%;
}
</style>
